# 图片验证码识别
import ddddocr
import base64
from PIL import Image
from io import BytesIO
import requests
import jsonpath
import os

"""
发送获取验证码请求
"""
def get_auth_code_request():
    data = {
        "method": "get",
        "url": os.environ["URL"]+"/captcha?_t=1761746424989"
    }
    response = requests.request(**data)
    sn = jsonpath.jsonpath(response.json(), '$..sn')[0]
    image = jsonpath.jsonpath(response.json(), '$..image')[0]
    return sn, image

"""
解析image得到验证码
"""
def dddd_ocr_text(image):
    # 步骤1：对image进行分割，得到头部和Base64编码的部分
    encode_data = image.split(",")[1]

    # 步骤2：解码Base64元数据
    decode_data = base64.b64decode(encode_data)

    # 步骤3：通过ddddocr来识别图片元数据
    ocr = ddddocr.DdddOcr() # 实例化
    text = ocr.classification(decode_data)
    return text

# 全局字典
sn_text_dict={}
# 执行次数
runs_number =0
"""
得到最终的sn和验证码
"""
def get_res_sn_captcha():

    # 判断第一次执行和失败重试的时候才会执行获取验证码
    if os.environ["ENV"] =="prod":
        global runs_number
        if not sn_text_dict or runs_number % 2 == 0:
            sn, image = get_auth_code_request()
            text = dddd_ocr_text(image)
            sn_text_dict["sn"] = sn
            sn_text_dict["captcha"] = text
        runs_number += 1
        return sn_text_dict
    elif os.environ["ENV"] =="test":
        sn = get_auth_code_request()[0]
        sn_text_dict["sn"] = sn
        sn_text_dict["captcha"] = "aaaa"
        return sn_text_dict


if __name__ == '__main__':
    print(get_res_sn_captcha(),get_res_sn_captcha())